
import operator

import Image
import ImageDraw
#from matplotlib import pyplot

from libs import constants

class RectangleVisualizer:
    def __init__(self, width, height, boxes):
        self.width = width
        self.height = height
        self.boxes = boxes
        self.image = Image.new("RGB", (width, height))
        self.draw = ImageDraw.Draw(self.image)
        self.image.paste("#ffffff", [0,0,width,height])
        
    def draw_box(self, x, y, box_no, scale, orient):
        #x = x * scale['x']
        #y = y * scale['y']
        ss = min(scale['x'], scale['y'])
        x = x * ss
        y = y * ss
        #w = 0
        #h = 0    
        if orient == 0:
            w = self.boxes[box_no]['w'] * ss
            h = self.boxes[box_no]['h'] * ss
        else:
            w = self.boxes[box_no]['h'] * ss            
            h = self.boxes[box_no]['w'] * ss    
        self.draw.rectangle([x,y,x+w,y+h], "#ff0000", "#000000")
        #self.image = self.image.transpose(Image.FLIP_TOP_BOTTOM)
        #self.image.resize(, resample)
        
    def draw_individual(self, individual):
        for i, box in enumerate(individual[constants.PHENOTYPE]):
            scale = dict()
            scale['x'] = self.width / float(individual[constants.WIDTH])
            scale['y'] = self.height / float(individual[constants.HEIGHT])
            self.draw_box(box['x'], box['y'], i, scale, individual[constants.GENOTYPE]['orient'][i])
            
    def save_to_file(self, output="output.png"):
        self.image.save(output)    

    def getPNGImage(self):
        self.image.save("output.png")
        f = open("output.png", "rb")
        image = f.read()
        f.close()
        return image

"""
class ParetoVisualizer:
    max_pareto_ranking = 0
    sorted_points = []
    
    def __init__(self, points, width=450, height=420):
        self.sorted_points = sorted(points, key=lambda x:(x[2]), reverse=True)
        self.sorted_points = sorted(self.sorted_points, key=lambda x:(x[0], x[1])) 
        #self.max_pareto_ranking = self.sorted_points[-1:][0][0]
        
        print "Sorted Points"
        for triple in self.sorted_points:
            print triple
        
        #[triple[1] for triple in list_tuples if triple[0] == i]
    
    def drawIndividuals(self):
        for i in range(1, self.max_pareto_ranking):
            pyplot.plot([triple[1] for triple in self.sorted_points if triple[0] == i], 
                        [triple[2] for triple in self.sorted_points if triple[0] == i] 
            )
            
        pyplot.scatter([triple[1] for triple in self.sorted_points if triple[0] == self.max_pareto_ranking], 
                       [triple[2] for triple in self.sorted_points if triple[0] == self.max_pareto_ranking] 
        )
    
        pyplot.savefig("dd2.png")
"""          